package admin_menus

import (
	"encoding/json"
	"gitee.com/theegg/go-brick/app/service/app"
	"gitee.com/theegg/go-brick/app/service/help/credis"
	"github.com/go-redis/redis/v8"
	"strconv"
)

var CacheKeyPrefix = TableName + "_"

// @title 从缓存 获取 指定管理角色 分配的菜单
// @description 如果缓存不存在　则从数据库取
// @return map[int64]*AdminMenus
func GetItemByRoleIdFromCache(roleId int64, superRoleOptions ...bool) (map[int64]*AdminMenus, error) {
	redisOp := credis.New().Tag(TableName)
	key := CacheKeyPrefix + "role_" + strconv.FormatInt(roleId, 10)
	data, errGet := redisOp.TGet(key)
	if errGet != nil {
		if errGet == redis.Nil {
			isSupperRole := false
			if len(superRoleOptions) > 0 && superRoleOptions[0] {
				isSupperRole = true
			}

			data, errDb := GetAdminMenusByRoleIdFromDb(roleId, isSupperRole)
			if errDb != nil {
				return nil, app.NewError(errDb)
			}

			jsonData, _ := json.Marshal(data)

			_, errSet := redisOp.TSet(key, jsonData)
			if errSet != nil {
				return nil, errSet
			}

			return data, nil
		}
		panic("Redis-" + errGet.Error())
	}

	var returnData map[int64]*AdminMenus
	jsonErr := json.Unmarshal(data, &returnData)
	if jsonErr != nil {
		return nil, app.NewError(jsonErr)
	}

	return returnData, nil
}

// @title DeleteCacheByRoleId
// @description 刷新指定的id
func DeleteCacheByRoleId(id int64) (bool, error) {
	redisOp := credis.New().Tag(TableName)
	key := CacheKeyPrefix + "role_" + strconv.FormatInt(id, 10)
	_, err := redisOp.TDel(redisOp.GetTag(), key)
	if err != nil {
		return false, err
	}

	return true, nil
}

// @title FlushTag
// @description 删除tag上所有的
func FlushCacheByTag() bool {
	redisOp := credis.New().Tag(TableName)
	return redisOp.FlushTag()
}
